// pages/address/address.js
Page({
  data: {
    region: ['请选择地址', '', ''],
    isEdit: false,  // 默认值为 false
  },

  onLoad() {
    // 从本地存储获取 isEdit 值
    const isEdit = wx.getStorageSync('isEdit');
    this.setData({ isEdit: isEdit });
  },

  regionChange(e) {
    this.setData({ region: e.detail.value });
  },

  formSubmit(e) {
    const formData = e.detail.value;
    const name = formData.name.trim();
    const phone = formData.phone.trim();
    const region = this.data.region;
    const detailAddress = formData.detailAddress.trim();

    // 调用校验函数
    const validationError = this.validateForm({ 
      name, 
      phone, 
      region, 
      detailAddress 
    });

    if (validationError) {
      wx.showToast({ title: validationError, icon: "none", duration: 2000 });
      return;
    }

    // 从本地存储获取用户ID
    const user = wx.getStorageSync('user');
    if (!user || !user._id) {
      wx.showToast({ title: '未获取到用户ID', icon: "none", duration: 2000 });
      return;
    }

    // 拼接地区信息
    const regionStr = region.join(' ');
    const address = { name, phone, region: regionStr, detailAddress };

    // 发送请求
    wx.request({
      url: 'http://localhost:3000/login/address',
      method: 'POST',
      data: { _id: user._id, address },
      success: (res) => {
        wx.showToast({ title: '地址添加成功,请返回', icon: 'success' });
        const targetUrl = this.data.isEdit 
          ? '/pages/userhome-buy/userhome-buy' 
          : '/pages/userhome/userhome';
        setTimeout(() => wx.redirectTo({ url: targetUrl }), 2000);
      },
      fail: (err) => {
        wx.showToast({ title: '地址添加失败', icon: 'none' });
      }
    });
  },

  // 新增的校验函数
  validateForm(data) {
    // 1. 检查必填项
    if (!data.name || !data.phone || !data.region || !data.detailAddress) {
      return '请填写完整信息';
    }
    // 2. 校验手机号
    if (!/^1[3-9]\d{9}$/.test(data.phone)) {
      return '请输入有效的11位手机号';
    }


    return null;
  },

  // 以下生命周期函数保持原样
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
});